package horm

import (
	"database/sql"
	"haochen233/horm/dialect"

	"haochen233/horm/log"
	"haochen233/horm/session"
)

type Engine struct {
	db      *sql.DB
	dialect dialect.Dialect
}

//NewEngine create a Engine
func NewEngine(driveName, dsn string) (e *Engine, err error) {
	db, err := sql.Open(driveName, dsn)
	if err != nil {
		log.Error(err)
	}

	//send a ping message to db ,ensure db conn alive
	err = db.Ping()
	if err != nil {
		log.Error(err)
	}

	dial, ok := dialect.GetDialect(driveName)
	if !ok {
		log.Errorf("dialect:%s Is Not Found", driveName)
	}

	e = &Engine{db: db, dialect: dial}
	log.Info("Connect database success")
	return e, nil
}

//Close close dbtabase connection
func (e *Engine) Close() {
	if err := e.db.Close(); err != nil {
		log.Error("Failed to close database")
	}
	log.Info("Close database success")
}

//NewSession Get a New Session
func (e *Engine) NewSession() *Session.Session {
	return Session.New(e.db, e.dialect)
}
